//
//  HGPromoteVC.m
//  RedWinMall
//
//  Created by HeDianZhao on 2018/8/10.
//  Copyright © 2018年 HeDianZhao. All rights reserved.
//

#import "HGPromoteVC.h"
#import <UShareUI/UShareUI.h>

@interface HGPromoteVC ()

@property (strong, nonatomic) UIImageView *bg_imageView;

@end

@implementation HGPromoteVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initSubViews];
}

- (void)initSubViews {
    
    self.title = @"我要推广";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:(UIBarButtonItemStyleDone) target:self action:@selector(cilkAction)];
    
    _bg_imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tuiguang"]];
    _bg_imageView.userInteractionEnabled = YES;
    _bg_imageView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavigationHeight);
    [self.view addSubview:_bg_imageView];

    [self initData];
}

// 获取URL
- (void)initData {
    
    [[LMJRequestManager sharedManager] POST:KBaseURL(@"user/code") parameters:nil completion:^(LMJBaseResponse *response) {
        
        if (response.responseModel.status == 1) {
            [self createCoreImage:response.responseModel.data];
        } else {
//            [XZProgressHUD showMessageCenter:response.errorMsg];
        }
    }];
}

///长按保存图片
- (void)savePhoto:(UILongPressGestureRecognizer *)tap {
    
    if (tap.state == UIGestureRecognizerStateBegan) {
        LEEAlert.alert.config.LeeContent(@"是否保存图片").LeeCancelAction(@"取消", nil).LeeAction(@"保存", ^{
            
            UIImage *image = [self getImage];
            [UIView animateWithDuration:0.25 animations:^{
                self.navigationController.navigationBar.hidden = NO;
            }];
            [self loadImageFinished:image];
            
        }).LeeShow();
    }else {
        NSLog(@"long pressTap state :end");
    }
}

- (void)loadImageFinished:(UIImage *)image {
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
//    [XZProgressHUD showSuccess:@"保存成功"];
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}


#pragma mark - 生成二维码
- (void)createCoreImage:(NSString *)codeStr {
    
    //1.生成coreImage框架中的滤镜来生产二维码
    CIFilter *filter=[CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    
    [filter setValue:[codeStr dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
    //4.获取生成的图片
    CIImage *ciImg=filter.outputImage;
    //放大ciImg,默认生产的图片很小
    
    //5.设置二维码的前景色和背景颜色
    CIFilter *colorFilter=[CIFilter filterWithName:@"CIFalseColor"];
    //5.1设置默认值
    [colorFilter setDefaults];
    [colorFilter setValue:ciImg forKey:@"inputImage"];
    [colorFilter setValue:[CIColor colorWithRed:0 green:0 blue:0] forKey:@"inputColor0"];
    [colorFilter setValue:[CIColor colorWithRed:1 green:1 blue:1] forKey:@"inputColor1"];
    //5.3获取生存的图片
    ciImg=colorFilter.outputImage;
    
    CGFloat width = 110 * kScale;
    UIImage *img = [self createNonInterpolatedUIImageFormCIImage:ciImg withSize:width];
    
    //7.1开启图形上下文
    UIGraphicsBeginImageContext(img.size);
    
    [img drawInRect:CGRectMake(0, 0, width, width)];
    //7.3在中心划入其他图片
    UIImage *centerImg=[UIImage imageNamed:@"LOGO"];
    
    CGFloat centerW=50;
    CGFloat centerH=50;
    CGFloat centerX=(width-50)*0.5;
    CGFloat centerY=(width -50)*0.5;
    
    [centerImg drawInRect:CGRectMake(centerX, centerY, centerW, centerH)];
    
    //7.4获取绘制好的图片
    UIImage *finalImg  =UIGraphicsGetImageFromCurrentImageContext();
    
    //7.5关闭图像上下文
    UIGraphicsEndImageContext();
    //设置图片
    
    CGFloat hegith = _bg_imageView.height - 212;
    if (iphonePlus_5_5) {
        hegith = 275+160;
    }
    
    if (iphoneX) {
        hegith = _bg_imageView.height - 240;
    }
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:finalImg];
    imageView.frame = CGRectMake(27 * kScale, hegith, imageView.width, imageView.height);
    
    [_bg_imageView addSubview:imageView];
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(savePhoto:)];
    longTap.minimumPressDuration = 0.8; //定义按的时间
    longTap.numberOfTouchesRequired = 1;
    [_bg_imageView addGestureRecognizer:longTap];
}


- (void)cilkAction {
    
    UIImage *images = [self getImage];
    [UIView animateWithDuration:0.25 animations:^{
        self.navigationController.navigationBar.hidden = NO;
    }];
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UIImage *image = images;
        UMShareImageObject *shareObject = [UMShareImageObject shareObjectWithTitle:nil descr:nil thumImage:image];
        shareObject.shareImage = image;
        messageObject.shareObject = shareObject;
        
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
                NSLog(@"************Share fail with error %@*********",error);
            }else{
                if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                    UMSocialShareResponse *resp = data;
                    //分享结果消息
                    NSLog(@"response message is %@",resp.message);
                    //第三方原始返回的数据
                    NSLog(@"response originalResponse data is %@",resp.originalResponse);
                    
                }else{
                    NSLog(@"response data is %@",data);
                }
            }
        }];
        
    }];
    
}

#pragma mark 参数view即我们要截取的控件以及控件上的所有视图
- (UIImage *)getImage {
    
    self.navigationController.navigationBar.hidden = YES;
    
    UIImage* image = nil;//最终返回的image
    
    //设置截取尺寸
    CGSize size = self.view.size;
    
    //高清处理
    UIGraphicsBeginImageContextWithOptions(size, YES, [UIScreen mainScreen].scale);
    [self.view.layer renderInContext: UIGraphicsGetCurrentContext()];
    
    //得到图片
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  image;
}



@end
